<template>
  <div class="dc-container">
    <el-dialog v-model="visible" width="50%"
      :fullscreen="false" :title="title" :close-on-click-modal="false"
      @open="onDialogOpen" @close="onDialogClose">
      
      <el-form ref="editForm" :model="form" :rules="rules" label-width="100px" :disabled="mode == 'view'">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="router.id" label="路由">
              <el-cascader v-model="form.router.id" :options="routerOptions"
                separator="/" placeholder="请选择路由" clearable filterable
                :props="{ label: 'name', value: 'id', children: 'children', checkStrictly: true, emitPath: false }"
                :style="{ width: '100%' }"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="name" label="名称">
              <el-input v-model="form.name" :maxLength="128" placeholder="请输入名称" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="code" label="编号">
              <el-input v-model="form.code" :maxLength="64" placeholder="请输入编号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="url" label="URL">
              <el-input v-model="form.url" :maxLength="128" placeholder="请输入URL" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="permission" label="权限">
              <el-input v-model="form.permission" :maxLength="32" placeholder="请输入权限" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item prop="canPermission" label="可以授权">
              <el-switch v-model="form.canPermission" active-value="1" inactive-value="0"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="isDefault" label="默认资源">
              <el-switch v-model="form.isDefault" active-value="1" inactive-value="0"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="isLocked" label="禁用">
              <el-switch v-model="form.isLocked" active-value="1" inactive-value="0"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item prop="remarks" label="备注信息">
              <el-input v-model="form.remarks" type="textarea" :rows="3" :maxLength="255" placeholder="请输入备注信息" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onSubmit" type="primary" v-show="mode != 'view'">保存</el-button>
          <el-button @click="onDialogClose" v-if="mode != 'view'">取消</el-button>
          <el-button @click="onDialogClose" v-if="mode == 'view'">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getResourceById, saveResource } from '@/api/sys/resource'
import BaseUI from '@/views/components/baseUI'
import { treeRouter } from '@/api/sys/router'

export default {
  extends: BaseUI,
  name: 'resource-form',
  components: {},
  data() {
    return {
      mode: 'add',
      form: this.initForm(),
      visible: false,
      title: '资源表',
      
      rules: {
        'router.id': [{ required: true, message: '路由不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        url: [{ required: true, message: 'URL不能为空', trigger: 'blur' }],
        canPermission: [{ required: true, message: '可以授权不能为空', trigger: 'change' }],
        isDefault: [{ required: true, message: '默认资源不能为空', trigger: 'change' }]
      },
      
      routerOptions: []
    }
  },
  props: {
    permission: {
      type: Object
    }
  },
  methods: {
    async onSubmit() {
      let validFlag = true;
      
      await this.$refs.editForm.validate((valid) => {
        if (!valid) {
          validFlag = false;
          return false;
        }
      });
      
      if (validFlag) {
        this.doSave();
      }
    },
    doSave() {
      this.setLoad();
      saveResource(this.form)
        .then((responseData) => {
          if (responseData.code == 100) {
            this.visible = false;
            this.showMessage({
              type: 'success',
              msg: '保存成功'
            });
            this.$emit('save-finished');
          } else {
            this.showMessage(responseData);
          }
          this.resetLoad();
        })
        .catch((error) => {
          this.outputError(error);
        });
    },
    getFormById(id) {
      this.setLoad();
      return new Promise((resolve) => {
        getResourceById(id)
          .then((responseData) => {
            let form = {};
            if (responseData.code == 100) {
              form = responseData.data;
            } else {
              this.showMessage(responseData);
            }
            this.resetLoad();
            resolve(form);
          })
          .catch((error) => {
            this.outputError(error);
          });
      });
    },
    onDialogClose() {
      this.visible = false;
    },
    onDialogOpen() {
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
      });
    },
    initForm() {
      return {
        id: null,
        name: '',
        code: '',
        url: '',
        permission: '',
        canPermission: '1',
        isDefault: '0',
        isLocked: '0',
        router: {
          id: null
        },
        remarks: ''
      }
    },
    async openView(id) {
      this.mode = 'view';
      this.title = `查看资源`;
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      };
      this.initOptions();
      this.visible = true;
    },
    async openEdit(id) {
      this.mode = 'edit';
      this.title = `修改资源`;
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      };
      this.initOptions();
      this.visible = true;
    },
    openAdd(parent) {
      this.mode = 'add';
      this.title = `添加资源`;
      this.form = this.initForm();
      this.initOptions();
      this.visible = true;
    },
    async openCopy(id) {
      this.mode = 'add';
      this.title = `添加资源`;
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      };
      this.initOptions();
      this.form.id = null;
      this.visible = true;
    },
    
    initRouterOptions() {
      let search_List = { params: [] };
      
      treeRouter(search_List).then((responseData) => {
        if (responseData.code == 100) {
          this.routerOptions = responseData.data;
        } else {
          this.showMessage(responseData);
        }
      });
    },
    
    initOptions() {
      this.initRouterOptions();
    }
  }
}
</script> 